<template>
	<div class="mainor">
		<div class="main_spac1" style="padding-bottom: 5px">
			<el-form
				:inline="true"
				:rules="rules"
				:model="monitorForm"
				class="demo-form-inline marginTop0"
				ref="userListFrom"
				label-width="100px"
			>
				<div class="main_spac1 padding0" style="padding-bottom: 5px">
					<div class="main_white padding10">
						<div class="main_crumbs boxdq">
							<div class="main_crumbs_l">
								<a href="javascript:;" @click="$router.back(-1)">
									<i class="el-icon-arrow-down"></i>返回
								</a>
								<em>|</em>
								<span>备货采购</span>
							</div>
						</div>
						<div class="marginTop15">
							<el-form-item label="采购方式" prop="form.mode">
								<el-select
									v-model.trim="monitorForm.form.mode"
									placeholder="采购方式"
									class="wid220"
									@change="
										(monitorForm.form.buyer_id = null),
											(monitorForm.form.supplier_id = null),
											(monitorForm.list = [])
									"
								>
									<el-option
										v-for="(mode, index) in info.mode"
										:key="index"
										:label="mode"
										:value="parseInt(index)"
									></el-option>
								</el-select>
							</el-form-item>
							<el-form-item
								label=""
								prop="form.buyer_id"
								v-if="monitorForm.form.mode == 1"
								:rules="rules.buyer_id"
							>
								<el-select
									v-model.trim="monitorForm.form.buyer_id"
									ref="company"
									placeholder="采购员"
									class="wid220"
									@change="selecta"
								>
									<el-option
										v-for="(buyer, index) in info.buyer"
										:key="index"
										:label="buyer"
										:value="parseInt(index)"
									></el-option>
								</el-select>
							</el-form-item>
							<el-form-item
								label=""
								prop="form.supplier_id"
								v-if="monitorForm.form.mode > 1"
								ref="company"
								:rules="rules.supplier_id"
							>
								<el-select
									v-model.trim="monitorForm.form.supplier_id"
									placeholder="供应商"
									class="wid220"
									@change="supplierChange"
								>
									<el-option
										v-for="(supplier, index) in info.supplier"
										:key="index"
										:label="supplier"
										:value="parseInt(index)"
									></el-option>
								</el-select>
							</el-form-item>
							<el-form-item
								label="采购日期"
								prop="form.purchase_time"
								:rules="rules.createTime"
							>
								<el-date-picker
									v-model="monitorForm.form.purchase_time"
									type="date"
									class="time220"
									:editable="false"
									placeholder="采购日期"
									value-format="yyyy-MM-dd"
									:clearable="false"
								/>
							</el-form-item>
							<div class="clearfix"></div>
							<div class="marginTop5">
								<el-form-item
									label="备注："
									prop="form.remark"
									class="marginRight0 marginTop10 remark_in"
								>
									<el-input
										v-model.trim="monitorForm.form.remark"
										placeholder="备注"
										clearable
									></el-input>
								</el-form-item>
							</div>
						</div>
					</div>
				</div>
				<div class="main_white padding10 marginTop10 marginBottom10">
					<div>
						<div class="main_white">
							<div class="mainor_sp boxha">
								<ul class="box">
									<li class="box">
										<span> <em>*</em>商品名称： </span>
										<el-autocomplete
											v-model="formsp.value"
											:trigger-on-focus="true"
											ref="searchSelect"
											@clear="$refs.searchSelect.$children[0].blur()"
											class="wid240 main_comm"
											:fetch-suggestions="
												(queryString, cb) => {
													querySearchAsync(queryString, cb);
												}
											"
											placeholder="请输入内容"
											clearable
											:highlight-first-item="true"
											value-key="name"
											@select="
												(item) => {
													handleSelect(item);
												}
											"
										>
											<template slot-scope="{ item }">
												<div class="main_name">
													<span>
														{{ item.goods.name }}【{{ item.spu_name.title }}】
													</span>
													<span
														class="main_addr"
														v-if="info.show_sku_code == 1"
														>{{ item.goods_spu_code }}</span
													>
												</div>
											</template>
										</el-autocomplete>
									</li>
									<li class="box">
										<span> <em>*</em>数量： </span>
										<el-input
											v-model.trim="formsp.num"
											ref="focusw2"
											placeholder="数量"
											clearable
											class="wid140"
											@keyup.enter.native="mainor_sp"
										></el-input>
									</li>
								</ul>
								<div class="marginBottom10">
									<el-button
										type="primary"
										@click="mainor_qr"
										:disabled="enterDisabled"
										>确认(回车)</el-button
									>
									<el-button
										class="reset marginLeft5"
										type="info"
										@click="reset"
										>重置</el-button
									>
								</div>
							</div>
							<div class="main_table marginTop0" style="min-height: 370px">
								<el-table
									ref="multipleTable"
									:data="monitorForm.list"
									element-loading-text="加载中"
									fit
									border
									highlight-current-row
									:header-cell-class-name="this.$verticaline"
								>
									<el-table-column label="序号" width="80">
										<template slot-scope="scope">{{
											scope.$index + 1
										}}</template>
									</el-table-column>
									<el-table-column
										label="名称"
										show-overflow-tooltip
										prop="name"
									>
										<template slot-scope="scope"
											>{{ scope.row.name }}【{{
												scope.row.spu_name
											}}】</template
										>
									</el-table-column>
									<el-table-column
										label="单位"
										show-overflow-tooltip
										prop="unit"
									/>
									<el-table-column label="近一次采购价" prop="purchase_price" />
									<el-table-column
										label="数量"
										prop="price"
										class-name="main_hei"
										min-width="200"
									>
										<template slot-scope="scope">
											<el-form-item
												:prop="'list.' + scope.$index + '.purchase_num'"
												:rules="rules.purchase_num"
												label-width="10px"
												label=" "
											>
												<el-input
													v-model.trim="scope.row.purchase_num"
													:ref="'purchase_num' + scope.row.goods_spu_id"
													placeholder="数量"
													class="wid110"
												></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column
										label="备注"
										prop="remark"
										width="350"
										class-name="main_hei"
									>
										<template slot-scope="scope">
											<el-form-item label-width="0" label="">
												<el-input
													v-model.trim="scope.row.remark"
													placeholder="备注"
													class="wid240"
												></el-input>
											</el-form-item>
											<el-link
												type="danger"
												@click="scdelete(scope.$index)"
												class="paddingTop20"
												>删除</el-link
											>
										</template>
									</el-table-column>
								</el-table>
							</div>

							<div class="newConBox_p200 paddingBottom10" id="newConBox">
								<div class="newConBox_h32">
									<div
										:class="[
											'mainor_pr boxdq newConBox ',
											{ on: searchBarFixed },
										]"
									>
										<div class="mainor_prl">
											<el-button
												:loading="btn_loading"
												type="primary"
												@click="preservation"
												v-repeatClick
												>保存</el-button
											>
											<el-button @click="$router.back(-1)">取消</el-button>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</el-form>
		</div>
	</div>
</template>

<script>
	const shuju = {
		list: {
			name: "",
			goods_id: "",
			goods_spu_id: "",
			spu_name: "",
			unit: "",
			purchase_price: "",
			purchase_num: "",
			remark: "",
			show: false,
		},
		form: {
			mode: 1,
			purchase_time: parseTime(new Date(), "{y}-{m}-{d}"),
			buyer_id: null,
			supplier_id: null,
			remark: "",
		},
		formsp: {
			name: [],
			girard: null,
			num: "",
			value: "",
			pid: "",
			category_id: "",
		},
	};

	import {
		purchase_base,
		purchase_add,
		purchase_checkPurchase,
		goods_getGoodsSpu,
	} from "@/api/purchasing/purchasingPurchase";
	import { apiUrl, objKeySort, Md5 } from "@/utils/public";
	import rules from "@/rules/purchasing/purchasingPurchase_add";
	// import { goods_getGoodsSpu } from "@/api/currency";
	import { parseTime, jsonStringifyBack } from "@/utils/index";

	export default {
		components: {},
		watch: {
			monitorForm: {
				deep: true,
				handler: function () {
					this.isEdit = true;
				},
			},
		},
		data() {
			return {
				// 验证
				rules,
				// 列表数据
				monitorForm: {
					form: {
						mode: 1,
						purchase_time: parseTime(new Date(), "{y}-{m}-{d}"),
						buyer_id: null,
						supplier_id: null,
						remark: "",
					},
					list: [],
				},
				info: [],
				order_price: "",
				// 商品搜索
				formsp: {
					name: [],
					girard: null,
					num: "",
					value: "",
					pid: "",
					category_id: "",
				},
				show: true,
				// 监听滚动
				searchBarFixed: false,
				// 确认回车按钮
				enterDisabled: true,
				isEdit: false,
				btn_loading: false,
			};
		},
		mounted() {
			window.addEventListener("scroll", this.handleScroll);
		},
		destroyed() {
			window.removeEventListener("scroll", this.handleScroll);
		},
		beforeRouteLeave(to, from, next) {
			if (this.isEdit) {
				setTimeout(() => {
					this.$confirm(
						"您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
						"提示",
						{
							confirmButtonText: "确定",
							cancelButtonText: "取消",
							type: "warning",
						}
					)
						.then(() => {
							// 正常跳转
							next();
						})
						.catch(() => {
							next(false);
						});
				}, 200);
			} else {
				next();
			}
		},
		created() {
			// 信息
			this.purchase_base();
		},
		methods: {
			selecta() {
				this.monitorForm.list = [];
			},
			supplierChange() {
				this.monitorForm.form.buyer_id = null;
				this.monitorForm.list = [];
			},
			// 监听滚动
			handleScroll() {
				let scrollTop =
					window.pageYOffset ||
					document.documentElement.scrollTop ||
					document.body.scrollTop;
				scrollTop + document.documentElement.clientHeight >
				document.getElementById("newConBox").offsetTop + 300
					? (this.searchBarFixed = false)
					: (this.searchBarFixed = true);
			},
			// 商品搜索
			querySearchAsync(queryString, cb) {
				if (
					this.monitorForm.form.buyer_id == null &&
					this.monitorForm.form.supplier_id == null
				) {
					this.$message.error("请选择采购员或者供应商");
					this.$refs.company.focus();
					cb([]);
					return;
				}
				if (queryString.trim() == "") {
					cb([]);
					return;
				}
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(
								Object.assign(apiUrl().name, { name: queryString.trim() })
							) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					{ name: queryString.trim() }
				);
				goods_getGoodsSpu(data).then((res) => {
					if (res.errcode == 0) {
						res.data.goods.map((e) => {
							e.name = e.goods.name + "【" + e.spu_unit.title + "】";
						});
						var results = res.data.goods;
						if (this.$refs.searchSelect) {
							this.$refs.searchSelect.activated = true;
						}
						cb(results);
					} else {
						this.$message.error(res.errmsg);
						cb([]);
					}
				});
			},
			// 商品选择
			handleSelect(item) {
				this.formsp.name = item;
				this.formsp.girard = item.id;
				this.formsp.pid = item.goods.pid;
				this.formsp.category_id = item.goods.category_id;
				this.purchase_checkPurchase();
			},
			purchase_checkPurchase() {
				let formsp = JSON.parse(JSON.stringify(this.formsp));
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(
								Object.assign(apiUrl().name, {
									buyer_id: this.monitorForm.form.buyer_id,
									goods_id: formsp.name.goods_id,
									supplier_id: this.monitorForm.form.supplier_id,
								})
							) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					{
						buyer_id: this.monitorForm.form.buyer_id,
						goods_id: formsp.name.goods_id,
						supplier_id: this.monitorForm.form.supplier_id,
					}
				);
				purchase_checkPurchase(data).then((res) => {
					if (res.errcode == 0) {
						this.order_price = res.data.price;
						this.enterDisabled = false;
						setTimeout(() => {
							this.$refs.focusw2.focus();
						}, 100);
					} else {
						this.reset();
						this.$message.error(res.errmsg);
					}
				});
			},
			// 商品选择确认(回车)
			mainor_sp(e) {
				if (!this.enterDisabled) {
					var keyCode = window.event ? e.keyCode : e.which;
					if (keyCode == 13) {
						this.mainor_qr();
					}
				}
			},
			// 点击添加
			mainor_qr() {
				this.enterDisabled = true;
				let formsp = JSON.parse(JSON.stringify(this.formsp));
				if (!formsp.name.name) {
					this.$message.error("请填写商品名称");
					this.$refs.searchSelect.focus();
					return;
				} else if (formsp.num == "") {
					this.$message.error("请填写数量");
					this.$refs.focusw2.focus();
					return;
				} else {
					let monitorForm_list = JSON.parse(
						JSON.stringify(this.monitorForm.list)
					);
					let ind = 0;
					if (monitorForm_list.length != 0) {
						monitorForm_list.map((e, index) => {
							if (e.goods_spu_id == formsp.girard) {
								ind = e.goods_spu_id;
								return;
							}
						});
						if (ind == 0) {
							this.handle(formsp);
						} else {
							setTimeout(() => {
								this.$refs["purchase_num" + ind].focus();
								this.reset();
								ind = 0;
							}, 100);
						}
					} else {
						this.handle(formsp);
					}
				}
			},
			handle(formsp) {
				let list = JSON.parse(JSON.stringify(shuju.list));
				list.name = formsp.name.goods.name;
				list.goods_id = formsp.name.goods_id;
				list.goods_spu_id = formsp.name.id;
				list.spu_name = formsp.name.spu_name.title;
				list.unit = formsp.name.spu_unit.title;
				list.purchase_price = formsp.name.purchase_price;
				list.purchase_num = formsp.num;
				list.remark = formsp.name.remark;
				list.pid = formsp.pid;
				list.category_id = formsp.category_id;
				this.monitorForm.list.push(list);
				this.reset();
				setTimeout(() => {
					this.$refs.searchSelect.focus();
				}, 100);
			},
			reset() {
				this.formsp = JSON.parse(JSON.stringify(shuju.formsp));
				this.show = false;
				this.$nextTick(() => {
					this.show = true;
				});
			},
			// 删除
			scdelete(index) {
				this.monitorForm.list.splice(index, 1);
			},
			// 保存
			preservation(type) {
				this.$refs["userListFrom"].validate((valid) => {
					if (valid) {
						if (this.monitorForm.list.length == 0) {
							this.$message.error("请至少添加一个商品");
							return;
						}
						let form = JSON.parse(JSON.stringify(this.monitorForm.form));
						form.buyer_id = form.buyer_id ? form.buyer_id : 0;
						form.supplier_id = form.supplier_id ? form.supplier_id : 0;
						console.log("list", this.monitorForm.list);
						let sz = JSON.parse(
							JSON.stringify(this.monitorForm.list, jsonStringifyBack)
						);
						console.log("sz", sz);
						let list = sz.map((e) => {
							let { show, ...sz } = e;
							return { ...sz };
						});

						let data = Object.assign(
							{
								sign: Md5(
									objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
								),
							},
							apiUrl().name,
							form,
							{ list: JSON.stringify(list, jsonStringifyBack) }
						);
						this.btn_loading = true;
						purchase_add(data).then((res) => {
							this.btn_loading = false;
							if (res.errcode == 0) {
								this.$message({
									message: "添加成功",
									type: "success",
								});
								this.isEdit = false;
								this.$router.go(-1);
							} else {
								this.$message.error(res.errmsg);
							}
						});
					}
				});
			},
			// 信息
			purchase_base() {
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name
				);
				purchase_base(data).then((res) => {
					if (res.errcode == 0) {
						if (res.data.mode[3]) {
              // 去除直供选项
							delete res.data.mode[3];
						}
						this.info = res.data;
					} else {
						this.$message.error(res.errmsg);
					}
				});
			},
		},
	};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.main_name {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	padding: 5px 0;
	height: 50px;
	.main_addr {
		color: #999;
	}
	span {
		line-height: 20px;
		display: inline;
		height: 20px;
	}
}
.mainor {
	/deep/.el-button--default {
		border-color: $menuActiveText;
		color: $menuActiveText;
	}
	/deep/.el-form {
		margin-top: 10px;
		/deep/.el-form-item--mini.el-form-item,
		/deep/.el-form-item--small.el-form-item {
			margin-bottom: 10px;
		}
	}
	.remark_in {
		width: 100%;
		/deep/.el-form-item__content {
			width: 80%;
			.el-input {
				width: 57.9%;
			}
		}
	}
	.newConBox.on {
		width: calc(100% - 230px);
		padding-left: 0;
	}
	.main_crumbs_us {
		width: 240px;
	}
	.mainor_sp {
		ul {
			margin-right: 20px;
			li {
				margin-bottom: 10px;
				& > span {
					display: inline-block;
					line-height: 32px;
					width: 60px;
					color: $colour_18;
					font-size: $font_14;
					text-align: right;
					em {
						color: $colour_red;
						margin-right: 5px;
					}
				}
				&:first-child {
					& > span {
						width: 85px;
					}
				}
			}
		}
	}
	.main_table {
		/deep/.el-table--small td {
			padding-top: 0;
		}
		/deep/.el-form-item--small.el-form-item {
			margin-bottom: 16px;
			margin-top: 16px;
			margin-right: 0;
		}
	}
	.mainor_pr {
		margin-left: 10px;
		margin-bottom: 10px;
		/deep/.el-button--default {
			border-color: $subActive;
			color: $menuText;
			&:hover {
				border-color: $menuActiveText;
				color: $menuActiveText;
			}
		}
		.mainor_prr {
			font-size: $font_16;
			color: $colour_18;
			span {
				color: #fe3b3b;
				margin-left: 10px;
			}
		}
	}
}
</style>
